package com.aries.ui.view.title;

import com.aries.ui.util.*;
import com.aries.ui.view.alpha.AlphaImageView;
import com.aries.ui.view.alpha.AlphaTextView;
import com.aries.ui.view.title.util.ViewGroupUtils;
import com.aries.ui.widget.ResourceTable;
import ohos.aafwk.ability.Ability;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.render.BlendMode;
import ohos.agp.text.Font;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.Rect;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.Window;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;

public class TitleBarView extends ComponentContainer implements Component.EstimateSizeListener, ComponentContainer.ArrangeListener {

    /**
     * 默认透明度--5.0以上优化半透明状态栏一致
     */
    public static final int DEFAULT_STATUS_BAR_ALPHA = 102;
    /**
     * 默认文本颜色
     */
    private static final int DEFAULT_TEXT_COLOR = Color.BLACK.getValue();
    /**
     * 主标题size dp
     */
    private static final float DEFAULT_MAIN_TEXT_SIZE = 18;
    /**
     * 文本默认size dp
     */
    private static final float DEFAULT_TEXT_SIZE = 14;
    /**
     * 副标题默认size dp
     */
    private static final float DEFAULT_SUB_TEXT_SIZE = 12;
    /**
     * 左右padding dp--ToolBar默认16dp
     */
    private static final float DEFAULT_OUT_PADDING = 12;
    /**
     * 左右padding dp--ToolBar默认32dp
     */
    private static final float DEFAULT_CENTER_GRAVITY_LEFT_PADDING = 24;
    /**
     * 状态栏高度
     */
    private int mStatusBarHeight;
    /**
     * TitleBarView实际占用宽度
     */
    private int mScreenWidth;

    private Context mContext;
    /**
     * 自定义View-状态栏View-用于单独设置颜色
     */
    private Component mVStatus;
    /**
     * 左边容器
     */
    private DirectionalLayout mLLayoutLeft;
    /**
     * 中间容器
     */
    private DirectionalLayout mLLayoutCenter;
    /**
     * 右边容器
     */
    private DirectionalLayout mLLayoutRight;
    /**
     * 左边TextView
     */
    private AlphaTextView mTvLeft;
    /**
     * 主标题
     */
    private Text mTvTitleMain;
    /**
     * 副标题
     */
    private Text mTvTitleSub;
    /**
     * 右边TextView
     */
    private AlphaTextView mTvRight;
    /**
     * 下方下划线
     */
    private Component mVDivider;

    /**
     * 是否增加状态栏高度
     */
    private boolean mStatusBarPlusEnable = true;
    /**
     * 设置状态栏浅色或深色模式类型标记;>0则表示支持模式切换
     */
    private int mStatusBarModeType = StatusBarUtil.STATUS_BAR_TYPE_DEFAULT;
    /**
     * xml属性
     */
    private boolean mImmersible = false;
    private int mOutPadding;
    private int mActionPadding;
    /**
     * 中间部分是Layout左右padding
     */
    private int mCenterLayoutPadding;
    /**
     * 中间部分是否左对齐--默认居中
     */
    private boolean mCenterGravityLeft = false;
    /**
     * 中间部分左对齐是Layout左padding
     */
    private int mCenterGravityLeftPadding;
    /**
     * 是否浅色状态栏(黑色文字及图标)
     */
    private boolean mStatusBarLightMode = false;
    private float mViewPressedAlpha;

    private ShapeElement mStatusBackground;
    private ShapeElement mDividerBackground;
    private int mDividerHeight;
    private boolean mDividerVisible;

    private String mLeftText;
    private int mLeftTextSize;
    private ColorStateList mLeftTextColor;
    private ShapeElement mLeftTextBackground;
    private Element mLeftTextDrawable;
    private ColorStateList mLeftTextDrawableTint;
    private BlendMode mLeftTextDrawableTintMode;
    private int mLeftTextDrawableWidth;
    private int mLeftTextDrawableHeight;
    private int mLeftTextDrawablePadding;

    private String mTitleMainText;
    private int mTitleMainTextSize;
    private ColorStateList mTitleMainTextColor;
    private ShapeElement mTitleMainTextBackground;
    private boolean mTitleMainTextFakeBold;
    private boolean mTitleMainTextMarquee;

    private String mTitleSubText;
    private int mTitleSubTextSize;
    private ColorStateList mTitleSubTextColor;
    private ShapeElement mTitleSubTextBackground;
    private boolean mTitleSubTextFakeBold;
    private boolean mTitleSubTextMarquee;

    private String mRightText;
    private int mRightTextSize;
    private ColorStateList mRightTextColor;
    private ShapeElement mRightTextBackground;
    private Element mRightTextDrawable;
    private ColorStateList mRightTextDrawableTint;
    private BlendMode mRightTextDrawableTintMode;
    private int mRightTextDrawableWidth;
    private int mRightTextDrawableHeight;
    private int mRightTextDrawablePadding;

    private int mActionTextSize;
    private ColorStateList mActionTextColor;
    private ShapeElement mActionTextBackground;
    private ColorStateList mActionTint;
    private BlendMode mActionTintMode;
    private Rect mTitleContainerRect;
    private ResourceUtil mResourceUtil;
    private int mHeight = - 1;

    public TitleBarView(Context context) {
        this(context, null, "");
    }

    public TitleBarView(Context context, AttrSet attrSet) {
        this(context, attrSet, "");
    }

    public TitleBarView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        this.mContext = context;
        this.mResourceUtil = new ResourceUtil(mContext);
        initAttributes(context, attrSet);
        initView(context);
        setViewAttributes(context);

        setArrangeListener(this);
        setEstimateSizeListener(this);
    }

    /**
     * 判断父控件是否包含某个子View
     *
     * @param father 父控件
     * @param child 子控件
     * @return 某个子View
     */
    public static boolean hasChildView(ComponentContainer father, Component child) {
        boolean had = false;
        try {
            had = father.getChildIndex(child) != - 1;
        } catch (Exception e) {
        }
        return had;
    }

    /**
     * 获取状态栏高度
     *
     * @return 状态栏高度
     */
    @Deprecated
    public int getStatusBarHeight() {
        return StatusBarUtil.getStatusBarHeight(mContext);
    }

    private void initAttributes(Context context, AttrSet attrs) {
        mImmersible = AttrUtils.getBooleanFromAttr(attrs, "title_immersible", true);
        mStatusBarPlusEnable = AttrUtils.getBooleanFromAttr(attrs, "title_statusBarPlusEnable", true);
        mOutPadding = AttrUtils.getDimensionFromAttr(attrs, "title_outPadding", dip2px(DEFAULT_OUT_PADDING));
        mActionPadding = AttrUtils.getDimensionFromAttr(attrs, "title_actionPadding", dip2px(2));
        mCenterLayoutPadding = AttrUtils.getDimensionFromAttr(attrs, "title_centerLayoutPadding", dip2px(2));
        mCenterGravityLeft = AttrUtils.getBooleanFromAttr(attrs, "title_centerGravityLeft", false);
        mCenterGravityLeftPadding = AttrUtils.getDimensionFromAttr(attrs, "title_centerGravityLeftPadding", dip2px(DEFAULT_CENTER_GRAVITY_LEFT_PADDING));
        mStatusBarLightMode = AttrUtils.getBooleanFromAttr(attrs, "title_statusBarLightMode", false);
        mViewPressedAlpha = AttrUtils.getFloatFromAttr(attrs, "title_viewPressedAlpha", mResourceUtil.getAttrFloat(ResourceTable.String_pressedAlpha));

        mStatusBackground = (ShapeElement) AttrUtils.getElementFromAttr(attrs, "title_statusBackground", null);
        //不确定title_dividerBackground是颜色还是shape,需要判断一下
        String str = AttrUtils.getStringFromAttr(attrs, "title_dividerBackground", "");
        if (str.contains("$color:")) {
            //说明是颜色
            ShapeElement shape = new ShapeElement();
            int color = AttrUtils.getColorFromAttr(attrs, "title_dividerBackground", 0);
            shape.setRgbColor(RgbColor.fromArgbInt(color));
            mDividerBackground = shape;
        } else {
            //说明是shape
            mDividerBackground = (ShapeElement) AttrUtils.getElementFromAttr(attrs, "title_dividerBackground", null);
        }
        mDividerHeight = AttrUtils.getDimensionFromAttr(attrs, "title_dividerHeight", dip2px(1f));
        mDividerVisible = AttrUtils.getBooleanFromAttr(attrs, "title_dividerVisible", true);

        mLeftText = AttrUtils.getStringFromAttr(attrs, "title_leftText", " ");
        mLeftTextSize = AttrUtils.getDimensionFromAttr(attrs, "title_leftTextSize", dip2px(DEFAULT_TEXT_SIZE));

        int[] def1 = new int[] {AttrUtils.getColorFromAttr(attrs, "title_leftTextColor", 0)};
        mLeftTextColor = def1[0] != 0 ? new ColorStateList(new int[0][0], def1) : null;

        mLeftTextBackground = (ShapeElement) AttrUtils.getElementFromAttr(attrs, "title_leftTextBackground", null);
        mLeftTextDrawable = (PixelMapElement) AttrUtils.getElementFromAttr(attrs, "title_leftTextDrawable", null);

        int[] def2 = new int[] {AttrUtils.getColorFromAttr(attrs, "title_leftTextDrawableTint", 0)};
        mLeftTextDrawableTint = def2[0] != 0 ? new ColorStateList(new int[0][0], def2) : null;

        mLeftTextDrawableTintMode = parseTintMode(AttrUtils.getIntegerFromAttr(attrs, "title_leftTextDrawableTintMode", - 1), mLeftTextDrawableTintMode);
        mLeftTextDrawableWidth = AttrUtils.getDimensionFromAttr(attrs, "title_leftTextDrawableWidth", - 1);
        mLeftTextDrawableHeight = AttrUtils.getDimensionFromAttr(attrs, "title_leftTextDrawableHeight", - 1);
        mLeftTextDrawablePadding = AttrUtils.getDimensionFromAttr(attrs, "title_leftTextDrawablePadding", dip2px(1));

        mTitleMainText = AttrUtils.getStringFromAttr(attrs, "title_titleMainText", "");
        mTitleMainTextSize = AttrUtils.getDimensionFromAttr(attrs, "title_titleMainTextSize", dip2px(DEFAULT_MAIN_TEXT_SIZE));

        int[] def3 = new int[] {AttrUtils.getColorFromAttr(attrs, "title_titleMainTextColor", 0)};
        mTitleMainTextColor = def3[0] != 0 ? new ColorStateList(new int[0][0], def3) : null;

        mTitleMainTextBackground = (ShapeElement) AttrUtils.getElementFromAttr(attrs, "title_titleMainTextBackground", null);
        mTitleMainTextFakeBold = AttrUtils.getBooleanFromAttr(attrs, "title_titleMainTextFakeBold", false);
        mTitleMainTextMarquee = AttrUtils.getBooleanFromAttr(attrs, "title_titleMainTextMarquee", false);

        mTitleSubText = AttrUtils.getStringFromAttr(attrs, "title_titleSubText", "");
        mTitleSubTextSize = AttrUtils.getDimensionFromAttr(attrs, "title_titleSubTextSize", dip2px(DEFAULT_SUB_TEXT_SIZE));

        int[] def4 = new int[] {AttrUtils.getColorFromAttr(attrs, "title_titleSubTextColor", 0)};
        mTitleSubTextColor = def4[0] != 0 ? new ColorStateList(new int[0][0], def4) : null;

        mTitleSubTextBackground = (ShapeElement) AttrUtils.getElementFromAttr(attrs, "title_titleSubTextBackground", null);
        mTitleSubTextFakeBold = AttrUtils.getBooleanFromAttr(attrs, "title_titleSubTextFakeBold", false);
        mTitleSubTextMarquee = AttrUtils.getBooleanFromAttr(attrs, "title_titleSMarquee", false);

        mRightText = AttrUtils.getStringFromAttr(attrs, "title_rightText", " ");
        mRightTextSize = AttrUtils.getDimensionFromAttr(attrs, "title_rightTextSize", dip2px(DEFAULT_TEXT_SIZE));

        int[] def5 = new int[] {AttrUtils.getColorFromAttr(attrs, "title_rightTextColor", 0)};
        mRightTextColor = def5[0] != 0 ? new ColorStateList(new int[0][0], def5) : null;

        mRightTextBackground = (ShapeElement) AttrUtils.getElementFromAttr(attrs, "title_rightTextBackground", null);
        mRightTextDrawable = AttrUtils.getElementFromAttr(attrs, "title_rightTextDrawable", null);

        int[] def6 = new int[] {AttrUtils.getColorFromAttr(attrs, "title_rightTextDrawableTint", 0)};
        mRightTextDrawableTint = def6[0] != 0 ? new ColorStateList(new int[0][0], def6) : null;

        mRightTextDrawableTintMode = parseTintMode(AttrUtils.getIntegerFromAttr(attrs, "title_rightTextDrawableTintMode", - 1), mRightTextDrawableTintMode);
        mRightTextDrawableWidth = AttrUtils.getDimensionFromAttr(attrs, "title_rightTextDrawableWidth", - 1);
        mRightTextDrawableHeight = AttrUtils.getDimensionFromAttr(attrs, "title_rightTextDrawableHeight", - 1);
        mRightTextDrawablePadding = AttrUtils.getDimensionFromAttr(attrs, "title_rightTextDrawablePadding", dip2px(1));

        mActionTextSize = AttrUtils.getDimensionFromAttr(attrs, "title_actionTextSize", dip2px(DEFAULT_TEXT_SIZE));

        int[] def7 = new int[] {AttrUtils.getColorFromAttr(attrs, "title_actionTextColor", 0)};
        mActionTextColor = def7[0] != 0 ? new ColorStateList(new int[0][0], def7) : null;

        mActionTextBackground = (ShapeElement) AttrUtils.getElementFromAttr(attrs, "title_actionTextBackground", null);

        int[] def8 = new int[] {AttrUtils.getColorFromAttr(attrs, "title_actionTint", 0)};
        mActionTint = def8[0] != 0 ? new ColorStateList(new int[0][0], def8) : null;

        mActionTintMode = parseTintMode(AttrUtils.getIntegerFromAttr(attrs, "title_actionTintMode", - 1), mActionTintMode);

    }

    public BlendMode parseTintMode(int value, BlendMode defaultMode) {
        switch (value) {
            case 3:
                return BlendMode.SRC_OVER;
            case 5:
                return BlendMode.SRC_IN;
            case 9:
                return BlendMode.SRC_ATOP;
            case 14:
                return BlendMode.MULTIPLY;
            case 15:
                return BlendMode.SCREEN;
            case 16:
                return BlendMode.PLUS;
            default:
                return defaultMode;
        }
    }

    /**
     * 初始化子View
     *
     * @param context context
     */
    private void initView(Context context) {
        int content = LayoutConfig.MATCH_CONTENT;
        int parent = LayoutConfig.MATCH_PARENT;

        LayoutConfig params = new LayoutConfig(content, parent);
        LayoutConfig dividerParams = new LayoutConfig(parent, mDividerHeight);

        mLLayoutLeft = new DirectionalLayout(context);
        mLLayoutLeft.setOrientation(Component.HORIZONTAL); //mLLayoutLeft默认水平方向
        mLLayoutCenter = new DirectionalLayout(context);
        mLLayoutCenter.setOrientation(Component.HORIZONTAL); //mLLayoutCenter默认水平方向
        mLLayoutRight = new DirectionalLayout(context);
        mLLayoutRight.setOrientation(Component.HORIZONTAL); //mLLayoutCenter默认水平方向

        mVStatus = new Component(context);
        mVDivider = new Component(context);

        mLLayoutLeft.setAlignment(LayoutAlignment.VERTICAL_CENTER);
        mLLayoutRight.setAlignment(LayoutAlignment.VERTICAL_CENTER);

        mTvLeft = new AlphaTextView(context);
        mTvLeft.setTextAlignment(TextAlignment.CENTER);
        mTvLeft.setMultipleLine(false);

        mTvTitleMain = new Text(context);
        mTvTitleSub = new Text(context);

        mTvRight = new AlphaTextView(context);
        mTvRight.setTextAlignment(TextAlignment.CENTER);
        mTvRight.setMultipleLine(false);

        mLLayoutLeft.addComponent(mTvLeft, params);
        mLLayoutRight.addComponent(mTvRight, params);

        //添加左边容器
        addComponent(mLLayoutLeft, params);
        //添加右边容器
        addComponent(mLLayoutRight, params);
        //添加中间容器
        addComponent(mLLayoutCenter, params);
        //添加下划线View
        addComponent(mVDivider, dividerParams);
        //添加状态栏View
        addComponent(mVStatus);
    }

    /**
     * 设置xml默认属性
     *
     * @param context context
     */
    private void setViewAttributes(Context context) {
        mScreenWidth = getEstimatedWidth();
        mStatusBarHeight = getNeedStatusBarHeight();

        if (context instanceof Ability) {
//            setImmersible((Ability) context, mImmersible);
            if (mStatusBarLightMode) {
                setStatusBarLightMode(true);
            }
        }
        setOutPadding(mOutPadding);
        setActionPadding(mActionPadding);
        setCenterLayoutPadding(mCenterLayoutPadding);
        setCenterGravityLeft(mCenterGravityLeft);
        setStatusBackground(mStatusBackground);
        setDividerHeight(mDividerHeight);
        setDividerVisible(mDividerVisible);
        setDividerBackground(mDividerBackground);
        setViewPressedAlpha(mViewPressedAlpha);

        setLeftText(mLeftText);
        setLeftTextSize(Text.TextSizeType.PX, mLeftTextSize);
        setLeftTextColor(DEFAULT_TEXT_COLOR);
        setLeftTextColor(mLeftTextColor);
        setLeftTextBackground(mLeftTextBackground);
        setLeftTextDrawable(mLeftTextDrawable);
        setLeftTextDrawableTint(mLeftTextDrawableTint);
        setLeftTextDrawableTintMode(mLeftTextDrawableTintMode);
        setLeftTextDrawableWidth(mLeftTextDrawableWidth);
        setLeftTextDrawableHeight(mLeftTextDrawableHeight);
        setLeftTextDrawablePadding(mLeftTextDrawablePadding);

        setTitleMainText(mTitleMainText);
        setTitleMainTextSize(Text.TextSizeType.PX, mTitleMainTextSize);
        setTitleMainTextColor(DEFAULT_TEXT_COLOR);
        setTitleMainTextColor(mTitleMainTextColor);
        setTitleMainTextBackground(mTitleMainTextBackground);
        setTitleMainTextFakeBold(mTitleMainTextFakeBold);
        setTitleMainTextMarquee(mTitleMainTextMarquee);

        setTitleSubText(mTitleSubText);
        setTitleSubTextSize(Text.TextSizeType.PX, mTitleSubTextSize);
        setTitleSubTextColor(DEFAULT_TEXT_COLOR);
        setTitleSubTextColor(mTitleSubTextColor);
        setTitleSubTextBackground(mTitleSubTextBackground);
        setTitleSubTextFakeBold(mTitleSubTextFakeBold);
        setTitleSubTextMarquee(mTitleSubTextMarquee);

        setRightText(mRightText);
        setRightTextSize(Text.TextSizeType.PX, mRightTextSize);
        setRightTextColor(DEFAULT_TEXT_COLOR);
        setRightTextColor(mRightTextColor);
        setRightTextBackground(mRightTextBackground);
        setRightTextDrawable(mRightTextDrawable);
        setRightTextDrawableTint(mRightTextDrawableTint);
        setRightTextDrawableWidth(mRightTextDrawableWidth);
        setRightTextDrawableHeight(mRightTextDrawableHeight);
        setRightTextDrawablePadding(mRightTextDrawablePadding);
    }

    /**
     * 获取Title的父容器的边框
     *
     * @return Rect
     */
    public Rect getTitleContainerRect() {
        if (mTitleContainerRect == null) {
            mTitleContainerRect = new Rect();
        }
        if (mLLayoutCenter == null) {
            mTitleContainerRect.set(0, 0, 0, 0);
        } else {
            ViewGroupUtils.getDescendantRect(this, mLLayoutCenter, mTitleContainerRect);
        }
        mTitleContainerRect.set(mTitleContainerRect.left + mLLayoutCenter.getPaddingLeft(), mTitleContainerRect.top, mTitleContainerRect.right, mTitleContainerRect.bottom);
        return mTitleContainerRect;
    }

    /**
     * 根据位置获取 LinearLayout
     *
     * @param alignment 参考{@link LayoutAlignment}
     * @return DirectionalLayout
     */
    public DirectionalLayout getDirectionalLayout(int alignment) {
        if (alignment == LayoutAlignment.LEFT || alignment == LayoutAlignment.START) {
            return mLLayoutLeft;
        } else if (alignment == LayoutAlignment.CENTER) {
            return mLLayoutCenter;
        } else if (alignment == LayoutAlignment.END || alignment == LayoutAlignment.RIGHT) {
            return mLLayoutRight;
        }
        return mLLayoutCenter;
    }

    /**
     * 返回虚拟导航栏高度
     *
     * @return 返回虚拟导航栏高度
     */
    public int getNavigationBarHeight() {
        return mHeight - mStatusBarHeight;
    }

    /**
     * 根据位置获取Text
     *
     * @param alignment 参考{@link TextAlignment}
     * @return 获取Text
     */
    public Text getTextView(int alignment) {
        if (alignment == TextAlignment.LEFT || alignment == TextAlignment.START) {
            return mTvLeft;
        } else if (alignment == (TextAlignment.CENTER | TextAlignment.TOP)) {
            return mTvTitleMain;
        } else if (alignment == (TextAlignment.CENTER | TextAlignment.BOTTOM)) {
            return mTvTitleSub;
        } else if (alignment == TextAlignment.END || alignment == TextAlignment.RIGHT) {
            return mTvRight;
        }
        return mTvTitleMain;
    }

    /**
     * 根据位置获取View
     *
     * @param gravity 参考{@link LayoutAlignment}
     * @return 获取View
     */
    public Component getView(int gravity) {
        if (gravity == LayoutAlignment.TOP) {
            return mVStatus;
        } else if (gravity == LayoutAlignment.BOTTOM) {
            return mVDivider;
        }
        return mVStatus;
    }

    /**
     * 获取设置状态栏文字图标样式模式
     *
     * @return >0则表示设置成功 参考{@link StatusBarUtil}
     */
    public int getStatusBarModeType() {
        return mStatusBarModeType;
    }

    public TitleBarView setImmersible(Ability activity, boolean immersible) {
        return setImmersible(activity, immersible, mStatusBarPlusEnable);
    }

    public TitleBarView setImmersible(Ability activity, boolean immersible, boolean isTransStatusBar) {
        return setImmersible(activity, immersible, isTransStatusBar, mStatusBarPlusEnable);
    }

    /**
     * 设置沉浸式状态栏，4.4以上系统支持
     *
     * @param activity Ability
     * @param immersible 是否沉浸
     * @param isTransStatusBar 是否透明状态栏 --xml未设置statusBackground 属性才会执行
     * @param isPlusStatusBar 是否增加状态栏高度--用于控制底部有输入框 (设置false/xml背景色必须保持和状态栏一致)
     * @return TitleBarView
     */
    public TitleBarView setImmersible(Ability activity, boolean immersible, boolean isTransStatusBar, boolean isPlusStatusBar) {
        this.mImmersible = immersible;
        this.mStatusBarPlusEnable = isPlusStatusBar;
        mStatusBarHeight = getNeedStatusBarHeight();
        if (activity == null) {
            return this;
        }
        //透明状态栏
        Window window = activity.getWindow();
        mVStatus.setLayoutConfig(new ComponentContainer.LayoutConfig(LayoutConfig.MATCH_PARENT, mStatusBarHeight));
        window.addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_STATUS);
        int now = window.getStatusBarVisibility();
        int val = (now & WindowManager.LayoutConfig.MARK_FULL_SCREEN) == WindowManager.LayoutConfig.MARK_FULL_SCREEN ? now ^ WindowManager.LayoutConfig.MARK_FULL_SCREEN : now;
        int systemUi = mImmersible ? now | WindowManager.LayoutConfig.MARK_FULL_SCREEN : val;
        window.setStatusBarVisibility(systemUi);
        if (mImmersible) {
            window.addFlags(WindowManager.LayoutConfig.MARK_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        }
        window.setStatusBarColor(! mImmersible ? Color.BLACK.getValue() : Color.TRANSPARENT.getValue());
        StatusBarUtil.fitsNotchScreen(window, mImmersible);
        int temp = isTransStatusBar ? 0 : 102;
        setStatusAlpha(immersible ? temp : 255);
        return this;
    }

    @Override
    public boolean onArrange(int l, int t, int width, int height) {
        //实时获取避免因横竖屏切换造成测量错误
        mScreenWidth = getEstimatedWidth();
        mStatusBarHeight = getNeedStatusBarHeight();
        int left = mLLayoutLeft.getEstimatedWidth();
        int right = mLLayoutRight.getEstimatedWidth();
        int center = mLLayoutCenter.getEstimatedWidth();

        //左边 中间 右边layout 顶部在状态栏以下 底部在下划线以上
        mLLayoutLeft.arrange(0, mStatusBarHeight / 2, left, getEstimatedHeight() - mDividerHeight);
        //右边layout 左边 整个控件宽度- layout本身宽度
        mLLayoutRight.arrange(mScreenWidth - right, mStatusBarHeight / 2, mScreenWidth, getEstimatedHeight() - mDividerHeight);

        boolean isMuchScreen = left + right + center >= mScreenWidth;

        if (isMuchScreen) {
            mLLayoutCenter.arrange(left, mStatusBarHeight / 2, mScreenWidth - right - left, getEstimatedHeight() - mDividerHeight);
        } else {
            if (left > right) {
                mLLayoutCenter.arrange(left, mStatusBarHeight / 2, mScreenWidth - left * 2, getEstimatedHeight() - mDividerHeight);
            } else {
                mLLayoutCenter.arrange(right, mStatusBarHeight / 2, mScreenWidth - right * 2, getEstimatedHeight() - mDividerHeight);
            }
        }

        mVDivider.setLeft(0);
        mVDivider.setTop(getEstimatedHeight() - mDividerHeight);
        mVDivider.setRight(getEstimatedWidth());
        mVDivider.setBottom(getEstimatedHeight());

        mVStatus.setLeft(0);
        mVStatus.setTop(0);
        mVStatus.setRight(getEstimatedWidth());
        mVStatus.setBottom(mStatusBarHeight);
        return true;
    }

    @Override
    public boolean onEstimateSize(int widthMeasureSpec, int heightMeasureSpec) {
        mStatusBarHeight = getNeedStatusBarHeight();
        //测量子控件宽高
//        estimateSize(widthMeasureSpec, heightMeasureSpec);
        //重新测量宽高--增加状态栏及下划线的高度开始
        //父容器为ConstraintLayout约束布局特殊处理
        if (mHeight <= 0) {
            mHeight = EstimateSpec.getSize(heightMeasureSpec) + mStatusBarHeight + mDividerHeight;
        }
        //普通的父容器正常操作
        if (isNormalParent()) {
            mHeight = EstimateSpec.getSize(heightMeasureSpec) + mStatusBarHeight + mDividerHeight;
        }
        setEstimatedSize(EstimateSpec.getSize(widthMeasureSpec), mHeight);
        //重新测量宽高--增加状态栏及下划线的高度结束

        mLLayoutLeft.estimateSize(EstimateSpec.getSize(widthMeasureSpec), mHeight);
        mLLayoutRight.estimateSize(EstimateSpec.getSize(widthMeasureSpec), mHeight);
        mVDivider.estimateSize(EstimateSpec.getSize(widthMeasureSpec), mDividerHeight);

        //重新测量左 中 右 宽度 保证中间布局 居正中
        mScreenWidth = getEstimatedWidth();
        int left = mLLayoutLeft.getEstimatedWidth();
        int right = mLLayoutRight.getEstimatedWidth();
        int center = mLLayoutCenter.getEstimatedWidth();

        //判断左、中、右实际占用宽度是否等于或者超过屏幕宽度
        boolean isMuchScreen = left + right + center >= mScreenWidth;
        if (mCenterGravityLeft) {
            return true;
        }
        //不设置中间布局左对齐才进行中间布局重新测量
        if (isMuchScreen) {
            center = mScreenWidth - left - right;
        } else {
            if (left > right) {
                center = mScreenWidth - 2 * left;
            } else {
                center = mScreenWidth - 2 * right;
            }
        }
        mLLayoutCenter.estimateSize(EstimateSpec.getSizeWithMode(center, EstimateSpec.PRECISE), heightMeasureSpec);

        return true;
    }

    /**
     * 设置TitleBarView高度--不包含状态栏及下划线
     *
     * @param height TitleBarView高度
     * @return 当前TitleBarView
     */
    public TitleBarView setTitleBarViewHeight(int height) {
        LayoutConfig params = getLayoutConfig();
        if (params != null) {
            if (params.height != height) {
                mHeight = - 1;
            }
            params.height = height;
            setLayoutConfig(params);
        }
        return this;
    }

    @Override
    public void setLayoutConfig(LayoutConfig params) {
        LayoutConfig par = getLayoutConfig();
        if (par != null && params != null && par.height != params.height) {
            mHeight = - 1;
        }
        super.setLayoutConfig(params);
    }

    /**
     * 设置当前TitleBarView的背景Element
     *
     * @param background 背景Element
     * @return 当前TitleBarView
     */
    public TitleBarView setBgDrawable(ShapeElement background) {
        return setViewBackground(this, background);
    }

    /**
     * 设置当前TitleBarView的背景颜色
     *
     * @param color 背景颜色
     * @return 当前TitleBarView
     */
    public TitleBarView setBgColor(int color) {
        ShapeElement element = new ShapeElement();
        element.setRgbColor(RgbColor.fromArgbInt(color));
        setBackground(element);
        return this;
    }

    /**
     * 设置当前TitleBarView的背景shape
     *
     * @param res 背景shape的资源Id
     * @return 当前TitleBarView
     */
    public TitleBarView setBgResource(int res) {
        setBackground(new ShapeElement(getContext(), res));
        return this;
    }

    /**
     * 距左右边距--根据具体情况设置
     *
     * @param paddingValue 左右边距
     * @return 当前TitleBarView
     */
    public TitleBarView setOutPadding(int paddingValue) {
        mOutPadding = paddingValue;
        boolean isEmpty1 = mLeftText == null || " ".equals(mLeftText);
        if (isEmpty1 && mLeftTextDrawable == null || mLLayoutLeft.getChildIndex(mTvLeft) != 0) {
            mLLayoutLeft.setPadding(mOutPadding, 0, 0, 0);
            mTvLeft.setPadding(0, 0, 0, 0);
        } else {
            mLLayoutLeft.setPadding(0, 0, 0, 0);
            mTvLeft.setPadding(mOutPadding, 0, mActionPadding, 0);
        }

        boolean isEmpty2 = mRightText == null || " ".equals(mRightText);
        if (isEmpty2 && mRightTextDrawable == null || mLLayoutRight.getChildIndex(mTvRight) != mLLayoutRight.getChildCount() - 1) {
            mLLayoutRight.setPadding(0, 0, mOutPadding, 0);
            mTvRight.setPadding(0, 0, 0, 0);
        } else {
            mLLayoutRight.setPadding(0, 0, 0, 0);
            mTvRight.setPadding(mActionPadding, 0, mOutPadding, 0);
        }
        return this;
    }

    /**
     * 标题部分距左右的边距
     *
     * @param centerLayoutPadding 边距
     * @return TitleBarView
     */
    public TitleBarView setCenterLayoutPadding(int centerLayoutPadding) {
        this.mCenterLayoutPadding = centerLayoutPadding;
        mLLayoutCenter.setPadding(mCenterLayoutPadding, mLLayoutCenter.getPaddingTop(), mCenterLayoutPadding, mLLayoutCenter.getPaddingBottom());
        return this;
    }

    /**
     * 设置中间是否左对齐
     *
     * @param enable 是否左对齐
     * @return TitleBarView
     */
    public TitleBarView setCenterGravityLeft(boolean enable) {
        this.mCenterGravityLeft = enable;
        mTvTitleMain.setTextAlignment(mCenterGravityLeft ? TextAlignment.LEFT : TextAlignment.CENTER);
        mLLayoutCenter.setAlignment(mCenterGravityLeft ? LayoutAlignment.LEFT | LayoutAlignment.VERTICAL_CENTER : LayoutAlignment.CENTER);
        mTvTitleSub.setTextAlignment(mCenterGravityLeft ? TextAlignment.LEFT : TextAlignment.CENTER);
        return setCenterGravityLeftPadding(mCenterGravityLeftPadding);
    }

    /**
     * 设置title 左边距--当设置setCenterGravityLeft(true)生效
     *
     * @param padding 左边距
     * @return TitleBarView
     */
    public TitleBarView setCenterGravityLeftPadding(int padding) {
        if (mCenterGravityLeft) {
            mCenterGravityLeftPadding = padding;
            mLLayoutCenter.setPadding(mCenterGravityLeftPadding, mLLayoutCenter.getPaddingTop(), mLLayoutCenter.getPaddingRight(), mLLayoutCenter.getPaddingBottom());
        } else {
            return setCenterLayoutPadding(mCenterLayoutPadding);
        }
        return this;
    }

    /**
     * 设置状态栏Light模式
     *
     * @param mStatusBarLightMode 是否Light模式
     * @return TitleBarView
     */
    public TitleBarView setStatusBarLightMode(boolean mStatusBarLightMode) {
        if (mContext instanceof Ability) {
            return setStatusBarLightMode((Ability) mContext, mStatusBarLightMode);
        }
        return this;
    }

    /**
     * 设置状态栏文字黑白颜色切换
     *
     * @param mActivity 环境
     * @param mStatusBarLightMode 状态栏Light模式
     * @return TitleBarView
     */
    public TitleBarView setStatusBarLightMode(Ability mActivity, boolean mStatusBarLightMode) {
        this.mStatusBarLightMode = mStatusBarLightMode;
        if (mActivity != null) {
            if (mStatusBarLightMode) {
                mStatusBarModeType = StatusBarUtil.setStatusBarLightMode(mActivity);
            } else {
                mStatusBarModeType = StatusBarUtil.setStatusBarDarkMode(mActivity);
            }
        }
        return this;
    }

    /**
     * 返回是否支持状态栏颜色切换
     *
     * @return 是否支持
     */
    public boolean isStatusBarLightModeEnable() {
        return StatusBarUtil.isSupportStatusBarFontChange();
    }

    /**
     * 设置view左右两边内边距
     *
     * @param actionPadding 左右两边内边距
     * @return TitleBarView
     */
    public TitleBarView setActionPadding(int actionPadding) {
        mActionPadding = actionPadding;
        return this;
    }

    /**
     * 设置状态栏背景
     *
     * @param drawable 背景
     * @return TitleBarView
     */
    public TitleBarView setStatusBackground(ShapeElement drawable) {
        mStatusBackground = drawable;
        return setViewBackground(mVStatus, mStatusBackground);
    }

    /**
     * 设置状态栏颜色
     *
     * @param color 状态栏颜色
     * @return TitleBarView
     */
    public TitleBarView setStatusBackgroundColor(int color) {
        ShapeElement element = new ShapeElement();
        element.setRgbColor(RgbColor.fromArgbInt(color));
        return setStatusBackground(element);
    }

    /**
     * 设置透明度
     *
     * @param alpha 透明度
     * @return TitleBarView
     */
    public TitleBarView setStatusAlpha(int alpha) {
        if (alpha < 0) {
            alpha = 0;
        } else if (alpha > 255) {
            alpha = 255;
        }
        return setStatusBackgroundColor(Color.argb(alpha, 0, 0, 0));
    }

    public TitleBarView setStatusBackgroundResource(int resId) {
        return setStatusBackground(mResourceUtil.getShapeDrawable(resId));
    }

    /**
     * 设置下划线背景
     *
     * @param drawable 下划线背景
     * @return TitleBarView
     */
    public TitleBarView setDividerBackground(ShapeElement drawable) {
        mDividerBackground = drawable;
        return setViewBackground(mVDivider, mDividerBackground);
    }

    /**
     * 设置下划线背景颜色
     *
     * @param color 背景颜色
     * @return TitleBarView
     */
    public TitleBarView setDividerBackgroundColor(int color) {
        ShapeElement element = new ShapeElement();
        element.setRgbColor(RgbColor.fromArgbInt(color));
        return setDividerBackground(element);
    }

    public TitleBarView setDividerBackgroundResource(int resId) {
        return setDividerBackground(mResourceUtil.getShapeDrawable(resId));
    }

    public TitleBarView setDividerHeight(int dividerHeight) {
        mDividerHeight = dividerHeight;
        mVDivider.getLayoutConfig().height = mDividerHeight;
        return this;
    }

    public TitleBarView setDividerVisible(boolean visible) {
        mDividerVisible = visible;
        mVDivider.setVisibility(visible ? VISIBLE : HIDE);
        return this;
    }

//    public TitleBarView setTextColor(ColorStateList colors) {
//        return setLeftTextColor(colors)
//                .setTitleMainTextColor(colors)
//                .setTitleSubTextColor(colors)
//                .setRightTextColor(colors)
//                .setActionTextColor(colors);
//    }

    /**
     * 设置view点击按下时alpha变化
     *
     * @param alpha 透明度
     * @return TitleBarView
     */
    public TitleBarView setViewPressedAlpha(float alpha) {
        if (alpha > 1) {
            alpha = 1.0f;
        } else if (alpha < 0) {
            alpha = 0f;
        }
        this.mViewPressedAlpha = alpha;
        mTvLeft.getDelegate().getAlphaViewHelper().setPressedAlpha(mViewPressedAlpha);
        mTvRight.getDelegate().getAlphaViewHelper().setPressedAlpha(mViewPressedAlpha);
        return this;
    }

    /**
     * 设置所有TextView的文本颜色--注意和其它方法的先后顺序
     *
     * @param color 文本颜色
     * @return TitleBarView
     */
    public TitleBarView setTextColor(int color) {
        return setLeftTextColor(color).setTitleMainTextColor(color).setTitleSubTextColor(color).setRightTextColor(color).setActionTextColor(color);
    }

    public TitleBarView setTextColorResource(int res) {
        return setTextColor(mResourceUtil.getColor(res));
    }

    public TitleBarView setLeftText(String title) {
        mLeftText = title;
        mTvLeft.setText(title);
        return setOutPadding(mOutPadding);
    }

    public TitleBarView setLeftText(int id) {
        return setLeftText(mResourceUtil.getText(id));
    }

    /**
     * 设置文字大小
     *
     * @param unit 文字单位{@link Text.TextSizeType}
     * @param size
     * @return TitleBarView
     */
    public TitleBarView setLeftTextSize(Text.TextSizeType unit, float size) {
        mTvLeft.setTextSize((int) size, unit);
        return this;
    }

    public TitleBarView setLeftTextSize(float size) {
        return setLeftTextSize(Text.TextSizeType.FP, size);
    }

    public TitleBarView setLeftTextColor(int color) {
        mTvLeft.setTextColor(new Color(color));
        return this;
    }

    /**
     * 设置文字状态颜色-如按下颜色变化
     *
     * @param colors 状态及对应颜色的列表
     * @return TitleBarView
     */
    public TitleBarView setLeftTextColor(ColorStateList colors) {
        if (colors != null) {
            mTvLeft.setTextColor(new Color(colors.mColors[0]));
        }
        return this;
    }

    public TitleBarView setLeftTextColorResource(int res) {
        return setLeftTextColor(mResourceUtil.getColorStateList(res));
    }

    public TitleBarView setLeftTextBackground(ShapeElement drawable) {
        mLeftTextBackground = drawable;
        return setViewBackground(mTvLeft, mLeftTextBackground);
    }

    public TitleBarView setLeftTextBackgroundColor(int color) {
        ShapeElement element = new ShapeElement();
        element.setRgbColor(RgbColor.fromArgbInt(color));
        return setLeftTextBackground(element);
    }

    public TitleBarView setLeftTextBackgroundResource(int resId) {
        return setLeftTextBackground(mResourceUtil.getShapeDrawable(resId));
    }

    /**
     * 设置左边图片资源
     *
     * @param drawable
     * @return TitleBarView
     */
    public TitleBarView setLeftTextDrawable(Element drawable) {
        mLeftTextDrawable = drawable;
        DrawableUtil.setDrawableWidthHeight(mLeftTextDrawable, mLeftTextDrawableWidth, mLeftTextDrawableHeight);

        Element[] drawables = mTvLeft.getAroundElements();
        mTvLeft.setAroundElements(mLeftTextDrawable, drawables[1], drawables[2], drawables[3]);
        setTextDrawableTint(mTvLeft, mLeftTextDrawableTint, mLeftTextDrawableTintMode);
        return setOutPadding(mOutPadding);
    }

    public TitleBarView setLeftTextDrawable(int resId) {
        return setLeftTextDrawable(mResourceUtil.getPixelMapElement(resId));
    }

    public TitleBarView setLeftTextDrawableTint(int color) {
        return setLeftTextDrawableTint(ColorStateList.valueOf(color));
    }

    public TitleBarView setLeftTextDrawableTint(ColorStateList colors) {
        if (colors == null) {
            return this;
        }
        mLeftTextDrawableTint = colors;
        return setTextDrawableTint(mTvLeft, mLeftTextDrawableTint, mLeftTextDrawableTintMode);
    }

    public TitleBarView setLeftTextDrawableTintResource(int res) {
        return setLeftTextDrawableTint(mResourceUtil.getColorStateList(res));
    }

    public TitleBarView setLeftTextDrawableTintMode(BlendMode mode) {
        if (mode == null) {
            return this;
        }
        mLeftTextDrawableTintMode = mode;
        return setTextDrawableTint(mTvLeft, mLeftTextDrawableTint, mLeftTextDrawableTintMode);
    }

    private TitleBarView setTextDrawableTint(Text textView, ColorStateList tint, BlendMode tintMode) {
        if (tint == null && tintMode == null) {
            return this;
        }
        Element[] drawables = textView.getAroundElements();
        for (Element item : drawables) {
            if (item != null) {
//                item = item.mutate();
                if (tint != null) {
                    DrawableUtil.setTintDrawable(item, tint);
                }
                if (tintMode != null) {
                    DrawableUtil.setTintMode(item, tintMode, tint != null ? tint.getDefaultColor() : Color.BLACK.getValue());
                }
            }
        }
        return this;
    }

    public TitleBarView setLeftTextDrawableWidth(int width) {
        mLeftTextDrawableWidth = width;
        return setLeftTextDrawable(mLeftTextDrawable);
    }

    public TitleBarView setLeftTextDrawableHeight(int height) {
        mLeftTextDrawableHeight = height;
        return setLeftTextDrawable(mLeftTextDrawable);
    }

    public TitleBarView setLeftTextDrawablePadding(int drawablePadding) {
        this.mLeftTextDrawablePadding = drawablePadding;
        mTvLeft.setAroundElementsPadding(mLeftTextDrawablePadding);
        return this;
    }

    public TitleBarView setLeftTextPadding(int left, int top, int right, int bottom) {
        mTvLeft.setPadding(left, top, right, bottom);
        return this;
    }

    public TitleBarView setOnLeftTextClickListener(ClickedListener l) {
        mTvLeft.setClickedListener(l);
        return this;
    }

    public TitleBarView setLeftVisible(boolean visible) {
        mTvLeft.setVisibility(visible ? Component.VISIBLE : Component.HIDE);
        return this;
    }

    public TitleBarView setTitleMainText(int id) {
        return setTitleMainText(mResourceUtil.getText(id));
    }

    public TitleBarView setTitleMainText(String charSequence) {
        mTvTitleMain.setText(charSequence);
        if (hasChildView(mLLayoutCenter, mTvTitleMain)) {
            return this;
        }
        if (charSequence == null || "".equals(charSequence)) {
            return this;
        }
        //CollapsingTitleBarLayout 作为父控件则不进行操作
        if ((getComponentParent() != null && getComponentParent().getClass().getSimpleName().equals("CollapsingTitleBarLayout"))) {
            return this;
        }
        mLLayoutCenter.addComponent(mTvTitleMain, 0);
        //有主副标题竖直布局
        if (hasChildView(mLLayoutCenter, mTvTitleMain) && hasChildView(mLLayoutCenter, mTvTitleSub)) {
            mLLayoutCenter.setOrientation(DirectionalLayout.VERTICAL);
        }
        return this;
    }

    public TitleBarView setTitleMainTextSize(Text.TextSizeType unit, float titleMainTextSpValue) {
        mTvTitleMain.setTextSize((int) titleMainTextSpValue, unit);
        return this;
    }

    public TitleBarView setTitleMainTextColor(ColorStateList colors) {
        if (colors != null) {
            mTvTitleMain.setTextColor(new Color(colors.mColors[0]));
        }
        return this;
    }

    public TitleBarView setTitleMainTextColorResource(int res) {
        return setTitleMainTextColor(mResourceUtil.getColorStateList(res));
    }

    /**
     * 设置文字大小
     *
     * @param titleMainTextSpValue titleMainTextSpValue
     * @return TitleBarView
     */
    public TitleBarView setTitleMainTextSize(float titleMainTextSpValue) {
        return setTitleMainTextSize(Text.TextSizeType.FP, titleMainTextSpValue);
    }

    public TitleBarView setTitleMainTextColor(int color) {
        mTvTitleMain.setTextColor(new Color(color));
        return this;
    }

    public TitleBarView setTitleMainTextBackground(ShapeElement drawable) {
        mTitleMainTextBackground = drawable;
        return setViewBackground(mTvTitleMain, mTitleMainTextBackground);
    }

    public TitleBarView setTitleMainTextBackgroundColor(int color) {
        ShapeElement element = new ShapeElement();
        element.setRgbColor(RgbColor.fromArgbInt(color));
        return setTitleMainTextBackground(element);
    }

    public TitleBarView setTitleMainTextBackgroundResource(int resId) {
        return setTitleMainTextBackground(mResourceUtil.getShapeDrawable(resId));
    }

    /**
     * 设置粗体标题
     *
     * @param isFakeBold isFakeBold
     * @return TitleBarView
     */
    public TitleBarView setTitleMainTextFakeBold(boolean isFakeBold) {
        this.mTitleMainTextFakeBold = isFakeBold;
        if (isFakeBold) {
            Font.Builder builder = new Font.Builder("");
            Font font = builder.setWeight(Font.BOLD).build();
            mTvTitleMain.setFont(font);
        } else {
            mTvTitleMain.setFont(Font.DEFAULT);
        }
        return this;
    }

    public TitleBarView setTitleMainTextMarquee(boolean enable) {
        this.mTitleMainTextMarquee = enable;
        if (enable) {
            setTitleSubTextMarquee(false);
            mTvTitleMain.setMultipleLine(false);
            mTvTitleMain.setTruncationMode(Text.TruncationMode.AUTO_SCROLLING);
            mTvTitleMain.setFocusable(FOCUS_ENABLE);
            mTvTitleMain.setTouchFocusable(true);
            mTvTitleMain.requestFocus();
            mTvTitleMain.setFocusChangedListener(new FocusChangedListener() {
                @Override
                public void onFocusChange(Component component, boolean hasFocus) {
                    if (! hasFocus && mTitleMainTextMarquee) {
                        mTvTitleMain.requestFocus();
                    }
                }
            });
            //开启硬件加速
//            mTvTitleMain.setLayerType(Component.LAYER_TYPE_HARDWARE, null);
        } else {
            mTvTitleMain.setMultipleLine(false);
            mTvTitleMain.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END);
            mTvTitleMain.setFocusChangedListener(null);
            //关闭硬件加速
//            mTvTitleMain.setLayerType(Component.LAYER_TYPE_NONE, null);
        }
        return this;
    }

    public TitleBarView setTitleMainTextPadding(int left, int top, int right, int bottom) {
        mTvTitleMain.setPadding(left, top, right, bottom);
        return this;
    }

    public TitleBarView setTitleSubText(String charSequence) {
        if (charSequence == null || charSequence.isEmpty()) {
            mTvTitleSub.setVisibility(Component.HIDE);
        } else {
            mTvTitleSub.setVisibility(VISIBLE);
        }
        mTvTitleSub.setText(charSequence);
        //非空且还未添加副标题
        boolean empty = charSequence == null || charSequence.length() == 0;
        if (! empty && ! hasChildView(mLLayoutCenter, mTvTitleSub)) {
            if (hasChildView(mLLayoutCenter, mTvTitleMain)) {
                mTvTitleMain.setMultipleLine(false);
                mTvTitleSub.setMultipleLine(false);
            }
            mLLayoutCenter.addComponent(mTvTitleSub);
        }
        //有主副标题竖直布局
        if (hasChildView(mLLayoutCenter, mTvTitleMain) && hasChildView(mLLayoutCenter, mTvTitleSub)) {
            mLLayoutCenter.setOrientation(DirectionalLayout.VERTICAL);
        }
        return this;
    }

    public TitleBarView setTitleSubText(int id) {
        return setTitleSubText(mResourceUtil.getText(id));
    }

    /**
     * 设置文字大小
     *
     * @param unit 单位 参考{@link Text.TextSizeType}
     * @param value value
     * @return TitleBarView
     */
    public TitleBarView setTitleSubTextSize(Text.TextSizeType unit, float value) {
        mTvTitleSub.setTextSize((int) value, unit);
        return this;
    }

    public TitleBarView setTitleSubTextColor(ColorStateList colors) {
        if (colors != null) {
            mTvTitleSub.setTextColor(new Color(colors.mColors[0]));
        }
        return this;
    }

    public TitleBarView setTitleSubTextColorResource(int res) {
        return setTitleSubTextColor(mResourceUtil.getColorStateList(res));
    }

    public TitleBarView setTitleSubTextSize(float spValue) {
        return setTitleSubTextSize(Text.TextSizeType.FP, spValue);
    }

    public TitleBarView setTitleSubTextColor(int color) {
        mTvTitleSub.setTextColor(new Color(color));
        return this;
    }

    public TitleBarView setTitleSubTextBackground(ShapeElement drawable) {
        mTitleSubTextBackground = drawable;
        return setViewBackground(mTvTitleSub, mTitleSubTextBackground);
    }

    public TitleBarView setTitleSubTextBackgroundColor(int color) {
        ShapeElement element = new ShapeElement();
        element.setRgbColor(RgbColor.fromArgbInt(color));
        return setTitleSubTextBackground(element);
    }

    public TitleBarView setTitleSubTextBackgroundResource(int resId) {
        return setTitleSubTextBackground(mResourceUtil.getShapeDrawable(resId));
    }

    /**
     * 设置粗体标题
     *
     * @param isFakeBold isFakeBold
     * @return TitleBarView
     */
    public TitleBarView setTitleSubTextFakeBold(boolean isFakeBold) {
        this.mTitleSubTextFakeBold = isFakeBold;
        if (isFakeBold) {
            Font.Builder builder = new Font.Builder("");
            Font font = builder.setWeight(Font.BOLD).build();
            mTvTitleSub.setFont(font);
        } else {
            mTvTitleSub.setFont(Font.DEFAULT);
        }
        return this;
    }

    /**
     * 设置TextView 跑马灯
     *
     * @param enable enable
     * @return TitleBarView
     */
    public TitleBarView setTitleSubTextMarquee(boolean enable) {
        this.mTitleSubTextMarquee = enable;
        if (enable) {
            setTitleMainTextMarquee(false);
            mTvTitleSub.setMultipleLine(false);
            mTvTitleSub.setTruncationMode(Text.TruncationMode.AUTO_SCROLLING);
            mTvTitleSub.setFocusable(FOCUS_ENABLE);
            mTvTitleSub.setTouchFocusable(true);
            mTvTitleSub.requestFocus();
            mTvTitleSub.setFocusChangedListener(new FocusChangedListener() {
                @Override
                public void onFocusChange(Component component, boolean hasFocus) {
                    if (! hasFocus && mTitleSubTextMarquee) {
                        mTvTitleMain.requestFocus();
                    }
                }
            });
            //开启硬件加速
//            mTvTitleSub.setLayerType(Component.LAYER_TYPE_HARDWARE, null);
        } else {
            mTvTitleSub.setMultipleLine(false);
            mTvTitleSub.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END);
            mTvTitleSub.setFocusChangedListener(null);
            //关闭硬件加速
//            mTvTitleSub.setLayerType(Component.LAYER_TYPE_NONE, null);
        }
        return this;
    }

    public TitleBarView setOnCenterClickListener(ClickedListener l) {
        mLLayoutCenter.setClickedListener(l);
        return this;
    }

    public TitleBarView setRightText(String title) {
        mRightText = title;
        mTvRight.setText(title);
        return setOutPadding(mOutPadding);
    }

    public TitleBarView setRightText(int id) {
        return setRightText(mResourceUtil.getText(id));
    }

    /**
     * 设置文字大小
     *
     * @param unit 单位 参考{@link Text.TextSizeType}
     * @param size 大小
     * @return TitleBarView
     */
    public TitleBarView setRightTextSize(Text.TextSizeType unit, float size) {
        mTvRight.setTextSize((int) size, unit);
        return this;
    }

    public TitleBarView setRightTextSize(float size) {
        return setRightTextSize(Text.TextSizeType.FP, size);
    }

    public TitleBarView setRightTextColor(int color) {
        mTvRight.setTextColor(new Color(color));
        return this;
    }

    public TitleBarView setRightTextColor(ColorStateList colors) {
        if (colors != null) {
            mTvRight.setTextColor(new Color(colors.mColors[0]));
        }
        return this;
    }

    public TitleBarView setRightTextColorResource(int res) {
        return setRightTextColor(mResourceUtil.getColorStateList(res));
    }

    public TitleBarView setRightTextBackground(ShapeElement drawable) {
        mRightTextBackground = drawable;
        return setViewBackground(mTvRight, mRightTextBackground);
    }

    public TitleBarView setRightTextBackgroundColor(int color) {
        ShapeElement element = new ShapeElement();
        element.setRgbColor(RgbColor.fromArgbInt(color));
        return setRightTextBackground(element);
    }

    public TitleBarView setRightTextBackgroundResource(int resId) {
        return setRightTextBackground(mResourceUtil.getShapeDrawable(resId));
    }

    /**
     * 右边文本添加图片
     *
     * @param drawable 资源
     * @return TitleBarView
     */
    public TitleBarView setRightTextDrawable(Element drawable) {
        mRightTextDrawable = drawable;
        DrawableUtil.setDrawableWidthHeight(mRightTextDrawable, mRightTextDrawableWidth, mRightTextDrawableHeight);
        Element[] drawables = mTvRight.getAroundElements();
        mTvRight.setAroundElements(drawables[0], drawables[1], mRightTextDrawable, drawables[3]);
        setTextDrawableTint(mTvRight, mRightTextDrawableTint, mRightTextDrawableTintMode);
        return setOutPadding(mOutPadding);
    }

    public TitleBarView setRightTextDrawable(int resId) {
        return setRightTextDrawable(mResourceUtil.getPixelMapElement(resId));
    }

    public TitleBarView setRightTextDrawableTint(int color) {
        return setRightTextDrawableTint(ColorStateList.valueOf(color));
    }

    public TitleBarView setRightTextDrawableTint(ColorStateList colors) {
        if (colors == null) {
            return this;
        }
        mRightTextDrawableTint = colors;
        return setTextDrawableTint(mTvRight, mRightTextDrawableTint, mRightTextDrawableTintMode);
    }

    public TitleBarView setRightTextDrawableTintResource(int res) {
        return setRightTextDrawableTint(mResourceUtil.getColorStateList(res));
    }

    public TitleBarView setRightTextDrawableTintMode(BlendMode mode) {
        if (mode == null) {
            return this;
        }
        mRightTextDrawableTintMode = mode;
        return setTextDrawableTint(mTvRight, mRightTextDrawableTint, mRightTextDrawableTintMode);
    }

    public TitleBarView setRightTextDrawablePadding(int drawablePadding) {
        this.mRightTextDrawablePadding = drawablePadding;
        mTvRight.setAroundElementsPadding(mRightTextDrawablePadding);
        return this;
    }

    public TitleBarView setRightTextDrawableWidth(int width) {
        mRightTextDrawableWidth = width;
        return setRightTextDrawable(mRightTextDrawable);
    }

    public TitleBarView setRightTextDrawableHeight(int height) {
        mRightTextDrawableHeight = height;
        return setRightTextDrawable(mRightTextDrawable);
    }

    public TitleBarView setRightTextPadding(int left, int top, int right, int bottom) {
        mTvRight.setPadding(left, top, right, bottom);
        return this;
    }

    public TitleBarView setOnRightTextClickListener(ClickedListener l) {
        mTvRight.setClickedListener(l);
        return this;
    }

    public TitleBarView setRightVisible(boolean visible) {
        mTvRight.setVisibility(visible ? Component.VISIBLE : Component.HIDE);
        return this;
    }

    public TitleBarView setActionTextSize(int mActionTextSize) {
        this.mActionTextSize = mActionTextSize;
        return this;
    }

    public TitleBarView setActionTextColor(int mActionTextColor) {
        this.mActionTextColor = ColorStateList.valueOf(mActionTextColor);
        return this;
    }

    public TitleBarView setActionTextColor(ColorStateList mActionTextColor) {
        this.mActionTextColor = mActionTextColor;
        return this;
    }

    public TitleBarView setActionTextColorResource(int res) {
        return setActionTextColor(mResourceUtil.getColorStateList(res));
    }

    public TitleBarView setActionTextBackground(ShapeElement drawable) {
        this.mActionTextBackground = drawable;
        return this;
    }

    public TitleBarView setActionTextBackgroundColor(int color) {
        ShapeElement element = new ShapeElement();
        element.setRgbColor(RgbColor.fromArgbInt(color));
        return setActionTextBackground(element);
    }

    public TitleBarView setActionTextBackgroundResource(int resId) {
        return setActionTextBackground(mResourceUtil.getShapeDrawable(resId));
    }

    public TitleBarView setActionTint(int color) {
        return setActionTint(ColorStateList.valueOf(color));
    }

    public TitleBarView setActionTint(ColorStateList colors) {
        if (colors == null) {
            return this;
        }
        mActionTint = colors;
        return setActionTint();
    }

    public TitleBarView setActionTintResource(int res) {
        return setActionTint(mResourceUtil.getColorStateList(res));
    }

    public TitleBarView setActionTintMode(BlendMode mode) {
        if (mode == null) {
            return this;
        }
        mActionTintMode = mode;
        return setActionTint();
    }

    private TitleBarView setActionTint() {
        if (mActionTint == null && mActionTintMode == null) {
            return this;
        }
        int sizeLeft = mLLayoutLeft.getChildCount();
        int sizeCenter = mLLayoutCenter.getChildCount();
        int sizeRight = mLLayoutRight.getChildCount();
        for (int i = 0; i < sizeLeft; i++) {
            Component view = mLLayoutLeft.getComponentAt(i);
            if (view instanceof Text) {
                if (view != mTvLeft) {
                    setTextDrawableTint((Text) view, mActionTint, mActionTintMode);
                }
            } else if (view instanceof Image) {
                setImageTint((Image) view, mActionTint, mActionTintMode);
            }
        }
        for (int i = 0; i < sizeCenter; i++) {
            Component view = mLLayoutCenter.getComponentAt(i);
            if (view instanceof Text) {
                if (view != mTvTitleMain && view != mTvTitleSub) {
                    setTextDrawableTint((Text) view, mActionTint, mActionTintMode);
                }
            } else if (view instanceof Image) {
                setImageTint((Image) view, mActionTint, mActionTintMode);
            }
        }
        for (int i = 0; i < sizeRight; i++) {
            Component view = mLLayoutRight.getComponentAt(i);
            if (view instanceof Text) {
                if (view != mTvRight) {
                    setTextDrawableTint((Text) view, mActionTint, mActionTintMode);
                }
            } else if (view instanceof Image) {
                setImageTint((Image) view, mActionTint, mActionTintMode);
            }
        }
        return this;
    }

    private void setImageTint(Image imageView, ColorStateList tint, BlendMode tintMode) {
        if (imageView.getImageElement() == null) {
            return;
        }
        if (tint == null && tintMode == null) {
            return;
        }

        PixelMapElement drawable = (PixelMapElement) imageView.getImageElement();
        if (drawable != null && mActionTint != null) {
            drawable.setStateColorList(mActionTint.mStateSpecs, mActionTint.mColors);
            drawable.setStateColorMode(mActionTintMode != null ? mActionTintMode : BlendMode.SRC_ATOP);
            imageView.setImageElement(drawable);
        }
    }

    /**
     * 自定义左边部分布局
     *
     * @param action action
     * @return TitleBarView
     */
    public TitleBarView addLeftAction(Action action) {
        return addLeftAction(action, - 1);
    }

    public TitleBarView addLeftAction(Action action, int position) {
        Component view = inflateAction(action);
        if (view == null) {
            return this;
        }
        return addLeftAction(action, position, view.getLayoutConfig());
    }

    public TitleBarView addLeftAction(Action action, int width, int height) {
        Component view = inflateAction(action);
        if (view == null) {
            return this;
        }
        LayoutConfig params = view.getLayoutConfig();
        if (params == null) {
            params = generateDefaultLayoutParams();
        }
        params.width = width;
        params.height = height;
        return addLeftAction(action, - 1, params);
    }

    public TitleBarView addLeftAction(Action action, LayoutConfig params) {
        return addLeftAction(action, - 1, params);
    }

    public TitleBarView addLeftAction(Action action, int position, LayoutConfig params) {
        Component view = inflateAction(action);
        if (view == null) {
            return this;
        }
        if (params == null) {
            params = generateDefaultLayoutParams();
        }
        mLLayoutLeft.addComponent(view, position, params);
        return this;
    }

    /**
     * 自定义中间部分布局
     *
     * @param action  action
     * @return  TitleBarView
     */
    public TitleBarView addCenterAction(Action action) {
        return addCenterAction(action, - 1);
    }

    public TitleBarView addCenterAction(Action action, int position) {
        Component view = inflateAction(action);
        if (view == null) {
            return this;
        }
        return addCenterAction(action, position, view.getLayoutConfig());
    }

    public TitleBarView addCenterAction(Action action, int width, int height) {
        Component view = inflateAction(action);
        if (view == null) {
            return this;
        }
        LayoutConfig params = view.getLayoutConfig();
        if (params == null) {
            params = generateDefaultLayoutParams();
        }
        params.width = width;
        params.height = height;
        return addCenterAction(action, - 1, params);
    }

    public TitleBarView addCenterAction(Action action, LayoutConfig params) {
        return addCenterAction(action, - 1, params);
    }

    public TitleBarView addCenterAction(Action action, int position, LayoutConfig params) {
        Component view = inflateAction(action);
        if (view == null) {
            return this;
        }
        if (params == null) {
            params = generateDefaultLayoutParams();
        }
        mLLayoutCenter.addComponent(view, position, params);
        return this;
    }

    /**
     * 在标题栏右边添加action
     *
     * @param action action
     * @return TitleBarView
     */
    public TitleBarView addRightAction(Action action) {
        return addRightAction(action, - 1);
    }

    public TitleBarView addRightAction(Action action, int position) {
        Component view = inflateAction(action);
        if (view == null) {
            return this;
        }
        return addRightAction(action, position, view.getLayoutConfig());
    }

    public TitleBarView addRightAction(Action action, int width, int height) {
        Component view = inflateAction(action);
        if (view == null) {
            return this;
        }
        LayoutConfig params = view.getLayoutConfig();
        if (params == null) {
            params = generateDefaultLayoutParams();
        }
        params.width = width;
        params.height = height;
        return addRightAction(action, - 1, params);
    }

    public TitleBarView addRightAction(Action action, LayoutConfig params) {
        return addLeftAction(action, - 1, params);
    }

    public TitleBarView addRightAction(Action action, int position, LayoutConfig params) {
        Component view = inflateAction(action);
        if (view == null) {
            return this;
        }
        if (params == null) {
            params = generateDefaultLayoutParams();
        }
        mLLayoutRight.addComponent(view, position, params);
        return this;
    }

    protected LayoutConfig generateDefaultLayoutParams() {
        return new LayoutConfig(LayoutConfig.MATCH_CONTENT, LayoutConfig.MATCH_CONTENT);
    }

    /**
     * 通过action加载一个View
     *
     * @param action action
     * @return Component
     */
    private Component inflateAction(Action action) {
        Component view = null;
        Object obj = action.getData();
        if (obj == null) {
            return null;
        }
        if (obj instanceof Component) {
            view = (Component) obj;
        } else if (obj instanceof String) {
            AlphaTextView text = new AlphaTextView(getContext());
            text.setTextAlignment(TextAlignment.CENTER);
            text.setText((String) obj);
            text.setTextSize(mActionTextSize, Text.TextSizeType.PX);
            if (mActionTextColor != null) {
                text.setTextColor(new Color(mActionTextColor.mColors[0]));
            } else {
                text.setTextColor(new Color(DEFAULT_TEXT_COLOR));
            }
            text.getDelegate().getAlphaViewHelper().setPressedAlpha(mViewPressedAlpha);
            setViewBackground(text, mActionTextBackground);
            view = text;
            setTextDrawableTint(text, mActionTint, mActionTintMode);
        } else if (obj instanceof Element) {
            AlphaImageView img = new AlphaImageView(getContext());
            img.setScaleMode(Image.ScaleMode.CLIP_CENTER);
            img.setImageElement((Element) obj);
            img.getDelegate().getAlphaViewHelper().setPressedAlpha(mViewPressedAlpha);
            view = img;
            setImageTint(img, mActionTint, mActionTintMode);
        }
        assert view != null;
        view.setPadding(mActionPadding, 0, mActionPadding, 0);
        view.setTag(action);
        view.setClickedListener(action.getOnClickListener());
        return view;
    }

    /**
     * 设置view背景drawable
     *
     * @param view view
     * @param drawable TitleBarView
     * @return  TitleBarView
     */
    private TitleBarView setViewBackground(Component view, ShapeElement drawable) {
        if (view == null) {
            return this;
        }
        view.setBackground(drawable);
        return this;
    }

    /**
     * 获取屏幕宽度
     *
     * @return 幕宽度
     */
    public int getScreenWidth() {
        Display display = DisplayManager.getInstance().getDefaultDisplay(getContext()).get();
        return display.getAttributes().width;
    }

    /**
     * 获取真实需要的状态栏高度
     *
     * @return 状态栏高度
     */
    private int getNeedStatusBarHeight() {
        int status = StatusBarUtil.getStatusBarHeight(getContext());
//        int safe = NotchUtil.getSafeInsetTop(this);
//        return isNeedStatusBar() ? status >= safe ? status : safe : 0;
        return isNeedStatusBar() ? status : 0;
    }

    /**
     * 当TitleBarView的父容器为ConstraintLayout(约束布局)时TitleBarView新增的高度会变成状态栏高度2倍需做特殊处理--暂不知原因
     *
     * @return 暂不知原因
     */
    private boolean isNormalParent() {
        return ! (getComponentParent() != null && getComponentParent().getClass().getSimpleName().contains("ConstraintLayout"));
    }

    private boolean isNeedStatusBar() {
        return mImmersible && mStatusBarPlusEnable;
    }

    /**
     * 将dip或dp值转换为px值
     *
     * @param dipValue dp值
     * @return 转换值
     */
    private int dip2px(float dipValue) {
        Display display = DisplayManager.getInstance().getDefaultDisplay(getContext()).get();
        float scale = display.getAttributes().densityPixels;
        return (int) ((double)dipValue * (double)scale + 0.5d);
    }

    /**
     * 添加View以及相应的动作接口
     */
    public interface Action<T> {
        T getData();

        ClickedListener getOnClickListener();
    }

    public class ImageAction implements Action<Element> {

        private PixelMapElement mDrawable;
        private ClickedListener onClickListener;

        public ImageAction(PixelMapElement mDrawable, ClickedListener onClickListener) {
            this.mDrawable = mDrawable;
            this.onClickListener = onClickListener;
        }

        public ImageAction(int drawableId, ClickedListener onClickListener) {
            this.mDrawable = (PixelMapElement) mResourceUtil.getImageDrawable(drawableId);
            this.onClickListener = onClickListener;
        }

        public ImageAction(int resId) {
            this.mDrawable = (PixelMapElement) mResourceUtil.getImageDrawable(resId);
        }

        public ImageAction(PixelMapElement drawable) {
            this.mDrawable = drawable;
        }

        @Override
        public Element getData() {
            return mDrawable;
        }

        @Override
        public ClickedListener getOnClickListener() {
            return onClickListener;
        }

    }

    public class TextAction implements Action<CharSequence> {

        private String mText;
        private ClickedListener onClickListener;

        public TextAction(String mText, ClickedListener onClickListener) {
            this.mText = mText;
            this.onClickListener = onClickListener;
        }

        public TextAction(String mText) {
            this.mText = mText;
        }

        public TextAction(int mText) {
            this.mText = mResourceUtil.getText(mText);
        }

        public TextAction(int mText, ClickedListener onClickListener) {
            this.mText = mResourceUtil.getText(mText);
            this.onClickListener = onClickListener;
        }

        @Override
        public CharSequence getData() {
            return mText;
        }

        @Override
        public ClickedListener getOnClickListener() {
            return onClickListener;
        }

    }

    public static class ViewAction implements Action<Component> {

        private Component mView;
        private ClickedListener onClickListener;

        public ViewAction(Component mView, ClickedListener onClickListener) {
            this.mView = mView;
            this.onClickListener = onClickListener;
        }

        public ViewAction(Component mView) {
            this.mView = mView;
        }

        @Override
        public Component getData() {
            return mView;
        }

        @Override
        public ClickedListener getOnClickListener() {
            return onClickListener;
        }

    }
}
